<?php

namespace App\Console\Commands\OpenShop;

use App\Enums\OpenShop\FeishuMini\ProgrammingEnum;
use App\Library\Rms\RmsShopApi;
use App\Models\Common\MapNationalUniversitiesModel;
use App\Models\OpenShop\Common\SiteLocationMallModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopAddressModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopLocationModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserBaseInfoModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Facades\Excel;

class ImportUniversities extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wanggui:import-universities';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导入学校信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return void
     * @throws GuzzleException
     */
    public function handle()
    {
        ini_set('memory_limit', '2048M');

        $url = $this->ask('请输入excel地址');

        if (!$url) {
            $url = 'https://file.51kuafu.com/11/8f/e8152ff723958c146eeecfb6e35c4d580d8c56f075623d4ff64e672862a6.xlsx';
        }

        // 获取在线文件内容
        $tempData = (new Client())->request("get", $url)->getBody()->getContents();

        // 重命名文件
        $fileName = 'php_import_' . md5($url) . '_' . date('YmdHis', time()) . "." . array_reverse(explode('.', $url))[0];

        // 文件存储的路径
        $savePath = sys_get_temp_dir() . '/' . $fileName;

        // 存文件
        file_put_contents($savePath, $tempData);

        Excel::import(new SiteUniversities(), $savePath);

        // 删除文件
        @unlink($savePath);
    }
}

class SiteUniversities implements ToCollection
{

    private string $errMsg = '';


    public function collection(Collection $collection)
    {
        // 校验列名信息
        $this->checkHeader($collection->first());

        if ($this->errMsg) {
            dd($this->errMsg);
        }

        $num = 0;
        $collection->chunk(1000)->map(function ($chunk) use (&$num) {
            $chunk->map(function ($item, $row) use (&$num) {
                $row = $row + 1;

                if ($row == 1) {
                    return null;
                }
                // 常规内容校验
                list(
                    $province,
                    $city,
                    $district,
                    $name,
                    $created_year,
                    $belongTo,
                    $project985,
                    $projuct211,
                    $double,
                    $strong,
                    $important,
                    $shDot,
                    $bsDot,
                    $laboratory,
                    $mu,
                    $yxlx,
                    $bxlx,
                    $bxxz,
                    $email,
                    $address,
                    $url,
                    $phone,
                    $lng,
                    $lat,
                    $grade
                    ) = $item;

                $universitiesModel                        = new MapNationalUniversitiesModel();
                $universitiesModel->province              = (string)$province;
                $universitiesModel->city                  = (string)$city;
                $universitiesModel->district              = (string)$district;
                $universitiesModel->name                  = (string)$name;
                $universitiesModel->startData             = (string)$created_year;
                $universitiesModel->attachedTo            = (string)$belongTo;
                $universitiesModel->project985            = (string)$project985;
                $universitiesModel->project211            = (string)$projuct211;
                $universitiesModel->doubleFirstClass      = (string)$double;
                $universitiesModel->strongBasis           = (string)$strong;
                $universitiesModel->nationalKeyDiscipline = (int)$important;
                $universitiesModel->master                = (int)$shDot;
                $universitiesModel->doctoral              = (int)$bsDot;
                $universitiesModel->KeyLaboratory         = (int)$laboratory;
                $universitiesModel->space                 = (int)$mu;
                $universitiesModel->schoolType            = (string)$yxlx;
                $universitiesModel->educationType         = (string)$bxlx;
                $universitiesModel->educationNature       = (string)$bxxz;
                $universitiesModel->email                 = (string)$email;
                $universitiesModel->address               = (string)$address;
                $universitiesModel->website               = (string)$url;
                $universitiesModel->tel                   = (string)$phone;
                $universitiesModel->lon                   = (string)$lng;
                $universitiesModel->lat                   = (string)$lat;
                $universitiesModel->grade                 = ProgrammingEnum::GRADE_INVERSE_CODING_MAPPING[(string)$grade] ?? 2;
                $universitiesModel->wgNumber              = 'GX44' . str_pad(($num + 1), 6, '0', STR_PAD_LEFT);
                $universitiesModel->save();
                dump(++$num);

            })->filter();
        });
    }

    private function checkHeader(Collection $item)
    {
        $formColumn = [
            "省份",
            "城市",
            "区域",
            "院校名称",
            "建校时间",
            "隶属于",
            "985工程",
            "211工程",
            "双一流",
            "强基",
            "国家重点学科",
            "硕士点",
            "博士点",
            "重点实验室",
            "占地面积(亩)",
            "院校类型",
            "办学类型",
            "办学性质",
            "电子邮箱",
            "地址",
            "官方网址",
            "官方电话",
            "经度",
            "纬度",
            "高校分级",
        ];

        foreach ($formColumn as $k => $v) {
            $dataV = $item[$k] ?? '';

            if (strpos($dataV, $v) === false) {
                $this->errMsg .= sprintf("第%d列，列名错误。应为：%s，传入：%s", $k + 1, $v, $dataV) . PHP_EOL;
            }
        }
    }

}
